/*
 * Copyright (c) 2014 laidian. All Rights Reserved.
 * 
 * @author yaoyuming
 * 
 * @date 2020/8/27 0027
 */
package com.yao.security.config;

import com.yao.security.filter.ValidateCodeFilter;
import com.yao.security.handler.FailureHandler;
import com.yao.security.handler.SuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.Arrays;

/**
 * spring-boot-security 配置类 WebSecurityConfigurerAdapter是由Spring Security提供的Web应用安全配置的适配器
 * 
 * @author yaoyuming
 * @date 2020/8/27 0027 16:22
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private FailureHandler failureHandler;
    @Autowired
    private SuccessHandler successHandler;
    @Autowired
    private ValidateCodeFilter validateCodeFilter;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

         formSecurity(http);
//        httpSercurity(http);
    }

    private void httpSercurity(HttpSecurity http) throws Exception {
        http.httpBasic() // HttpBasic
            .and().authorizeRequests() // 授权配置
            .regexMatchers(whiteList()).permitAll().and().authorizeRequests().anyRequest() // 所有请求
            .authenticated(); // 都需要认证
    }

    private void formSecurity(HttpSecurity http) throws Exception {
        // 验证码过滤器在用户校验之前执行
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
            .formLogin() // 表单登录
            .loginPage("/login.html") // 登录跳转url
//            .loginPage("/authentication/require") // 登录跳转url
            .loginProcessingUrl("/login") // 处理表单登录url
            .successHandler(successHandler)
            .failureHandler(failureHandler)
            .and().authorizeRequests() // 授权配置
            .antMatchers(whiteList()).permitAll() // 无需认证
            .anyRequest() // 所有请求
            .authenticated() // 都需要认证
            .and().csrf().disable();

    }

    private String[] whiteList() {
        String[] s = {};
        return Arrays.asList("/login.html", "/css/**", "/*.ico", "/authentication/requir", "/code/image").toArray(s);
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}